<template>
  <div>
    <div id="info" ref="info">&nbsp;</div>
    <div id="map-con7" ref="mapCon7"></div>
  </div>
</template>

<script>
import Map from "ol/Map";
import { OSM, Vector as VectorSource } from "ol/source";
import { Vector as VectorLayer } from "ol/layer";
import View from "ol/View";
import { fromLonLat } from "ol/proj";
import { GeoJSON } from "ol/format"
import { Fill, Stroke, Style } from 'ol/style';

export default {
  name: "vector",
  data() {
    return {
      map: null,
    };
  },
  created() { },
  async mounted() {
    let that = this;
    let map = new Map({
      // layers: [
      //   new TileLayer({
      //     source: new OSM({
      //       wrapX: false, // Whether to wrap the world horizontally
      //     }),
      //   }),
      // ],
      target: this.$refs.mapCon7,
      view: new View({
        center: fromLonLat([4.8, 47.75]),
        zoom: 5,
      }),
    });

    this.map = map;

    const vectorLayer = new VectorLayer({
      background: '#1a2b39',
      source: new VectorSource({
        url: "https://openlayers.org/data/vector/ecoregions.json",
        format: new GeoJSON()
      }),
      style(feature) {
        const color = feature.get('COLOR_NNH') || "#eeeeee";
        return new Style({
          fill: new Fill({
            color
          })
        });
      }
    })

    map.addLayer(vectorLayer);

    const highLightStyle = new Style({
      stroke: new Stroke({
        color: 'rgba(255, 255, 255, 0.7)',
        width: 2
      })
    });

    const featureOverlay = new VectorLayer({
      source: new VectorSource(),
      map,
      style: highLightStyle
    });

    let highlight;
    const displayFeatureInfo = (pixel) => {
      vectorLayer.getFeatures(pixel).then((features) => {
        console.log("pixel : features", features);
        const feature = features.length ? features[0] : undefined;
        const info = that.$refs.info;
        if (features.length) {
          info.innerHTML = feature.get("ECO_NAME") + ": " + feature.get("NNH_NAME");

        } else {
          info.innerHTML = '&nbsp;';
        }
        if (feature != highlight) {
          if (highlight) {
            featureOverlay.getSource().removeFeature(highlight);
          }
          if (feature) {
            featureOverlay.getSource().addFeature(feature);
          }
          highlight = feature;
        }
      })
    };

    map.on("pointermove", (evt) => {
      if (evt.dragging) {
        console.log("drag");
        return;
      }
      console.log("move:", evt);
      const pixel = map.getEventPixel(evt.originalEvent);
      console.log("pixel", pixel)
      displayFeatureInfo(pixel);
    });

    map.on("click", (evt) => {
      console.log("click:", evt);
      displayFeatureInfo(evt.pixel)
    })
  },
  methods: {

  },
};
</script>

<style scope>
#map-con7 {
  height: 90vh;
}
</style>